// database/CategoryOperations.ts
import { relationalStore, dataPreferences, common } from '@kit.ArkData';
import { resourceManager } from '@kit.LocalizationKit';
import { taskPool } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

const STORE_CONFIG: relationalStore.StoreConfig = {
  name: 'CategoryDatabase.db',
  securityLevel: relationalStore.SecurityLevel.S1
};

let rdbStore: relationalStore.RdbStore;

class CategoryOperations {
  private static TAG = 'CategoryDB';

  // 初始化数据库
  static async initDB(context: common.Context) {
    try {
      rdbStore = await relationalStore.getRdbStore(context, STORE_CONFIG);
      await rdbStore.executeSql(
        `CREATE TABLE IF NOT EXISTS CategoryDto (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          category TEXT UNIQUE,
          descriptions TEXT,
          source TEXT
        )`
      );
    } catch (err) {
      hilog.error(0x0000, this.TAG, `DB init failed: ${err}`);
    }
  }

  // 核心操作方法
  static async saveAllCategories(context: common.Context, fileNames: string[]) {
    const prefs = dataPreferences.getPreferences(context, 'db_prefs');
    const isInitialized = await prefs.get('is_initialized', false);
    if (isInitialized) return;

    taskPool.execute(async () => {
      try {
        await this.initDB(context);

        for (const fileName of fileNames) {
          const jsonContent = await this.readJsonFile(context, fileName);
          const categories = JSON.parse(jsonContent);

          for (const category of categories) {
            await this.upsertCategory(category, fileName);
          }
        }

        await prefs.put('is_initialized', true);
        await prefs.flush();
      } catch (err) {
        hilog.error(0x0000, this.TAG, `Operation failed: ${err}`);
      }
    });
  }

  private static async readJsonFile(context: common.Context, fileName: string): Promise<string> {
    try {
      const resource = context.resourceManager;
      const rawFile = await resource.getRawFileContent(fileName);
      return String.fromCharCode(...rawFile);
    } catch (err) {
      hilog.error(0x0000, this.TAG, `Read JSON failed: ${err}`);
      return '';
    }
  }

  private static async upsertCategory(category: any, fileName: string) {
    const predicates = new relationalStore.RdbPredicates('CategoryDto');
    predicates.equalTo('category', category.category)
      .equalTo('source', fileName);

    const result = await rdbStore.query(predicates, ['id']);

    if (result.rowCount === 0) {
      await rdbStore.insert('CategoryDto', {
        category: category.category,
        descriptions: JSON.stringify(category.descriptions),
        source: fileName
      });
    } else {
      const updateValues = {
        descriptions: JSON.stringify(category.descriptions)
      };
      await rdbStore.update(updateValues, predicates);
    }
  }
}

export default CategoryOperations;